package image;

import java.awt.image.BufferedImage;
import java.util.HashMap;

import java.net.URL;

import javax.imageio.ImageIO;


/**
 * A resource manager for images in the game. A central resource that 
 * fetches images and caches them for later use.
 *  
 * @author Neil Cowzer
 */
public class ImageCache {
	// The single instance of this class
	private static ImageCache cache = new ImageCache();

	/**
	 * Get the single instance of this class
	 * @return cache
	 */
	public /*@ pure @*/ static ImageCache getCache() {
		return cache;
	}
	
	/** The cached sprite map */
	private HashMap<String, Image> sprites = new HashMap<String, Image>();

	/**
	 * Retrieve a sprite or if neccessary add another Sprite to the cache.
	 * 
	 * @param name the string reference of the sprite
	 * @return An instance of a sprite
	 */
	/*@ requires name != null
	    assignable cache
	    ensures true
	@*/
	public Image getSprite(String name) {
		// if sprite has been loaded, return the sprite
		if (sprites.get(name) != null){
			return (Image)sprites.get(name);
		}
		
		// Otherwise load the image
		BufferedImage img = null;
		URL url=null;
		try {
			url = getClass().getClassLoader().getResource(name);
			img = ImageIO.read(url);
			//System.out.println("Loaded!");
		} catch (Exception e) {
			System.out.println("Unable to load: " + name);
			System.out.println(e.getClass().getName()+" "+e.getMessage());
			System.exit(0);
			return null;
		}
		
		// Create a sprite and store it in the HashMap
		Image newSprite = new Image(img);
		sprites.put(name, newSprite);
		
		// return the image
		return (Image)sprites.get(name);
	}
	
	/**
	 * Update an image in the cache.
	 * 
	 * @param String "name" of file
	 * @param the image in question
	 */
	public void update(String ref, BufferedImage image){
		sprites.remove(ref);
		Image newSprite = new Image(image);
		sprites.put(ref, newSprite);
	}
	
	/** Clear ImageCaches.*/
	//@ ensures (* all the fields are empty *);
	public void clear(){
		sprites.clear();
	}
	
	
	/**
	 * Resize all the images as neccessary.
	 * 
	 * @param ratio_x ratio for which to expand the image in the x direction.
	 * @param ratio_y ratio for which to expand the image in the y direction.
	 */
	/*@ requires ratio_x != 0 && ratio_y != 0; 
	  	assignable (* all the images *);
	@*/
	public void resize(int ratio_x, int ratio_y){
		// iterate throught the list of all images
	}
	

}
